package session.stateless.FRM;

import entity.FRM.SupplierInvoice;
import entity.FRM.SupplierPayment;
import entity.SCM.MaterialOrder;
import entity.SCM.Supplier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
public class SupplierPaymentBean implements SupplierPaymentBeanLocal {
    @PersistenceContext 
    private EntityManager em;
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    
 
    @Override
    public Long createSupplierPayment(Long supplierInvoiceId, Double paymentAmount) {
        SupplierInvoice supplierInvoice =em.find(SupplierInvoice.class, supplierInvoiceId);
        
        SupplierPayment supplierPayment = new SupplierPayment();
        Date date = new Date();
        supplierPayment.setSupplierPaymentDate(dateFormat.format(date)); 
        supplierPayment.setSupplierPaymentAmount(paymentAmount);
        supplierPayment.setSupplierInvoice(supplierInvoice);
        em.persist(supplierPayment);
        
        supplierInvoice.setStateSupplierInvoice(SupplierInvoice.StateSupplierInvoice.Success);
        
        MaterialOrder materialOrder = supplierInvoice.getMaterialOrder();
        Supplier supplier = materialOrder.getSupplier();
        
        materialOrder.setMaterialOrderState(MaterialOrder.State.Paid);
        supplier.getSupplierPayments().add(supplierPayment);
        em.flush();
        
        return supplierPayment.getSupplierPaymentId();            
    }
    
    

    
    @Override
    public List<SupplierPayment> getAllSupplierPayments() {
        Query q = em.createQuery("SELECT c FROM SupplierPayment c");
        return q.getResultList();
    }

    @Override
    public List<SupplierPayment> getSupplierPaymentByName(String supplierName) {
        Supplier supplier = em.find(Supplier.class, supplierName);
        return supplier.getSupplierPayments();
    }

}
